package com.party.course.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.party.course.domain.RealNameInfo;
import com.party.course.vo.*;
import com.yeepay.yop.sdk.service.common.YopClient;
import com.yeepay.yop.sdk.service.common.YopClientBuilder;
import com.yeepay.yop.sdk.service.common.request.YopRequest;
import com.yeepay.yop.sdk.service.common.response.YopResponse;

import com.yeepay.yop.sdk.service.common.response.YosUploadResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

import static cn.hutool.core.convert.Convert.toHex;

/**
 * 进件
 */
public class Example {

    // 该Client线程安全，请使用单例模式，多次请求共用
    private static final YopClient client = YopClientBuilder.builder().build();
    private static final Logger LOGGER = LoggerFactory.getLogger(Example.class);

    public static void main(String[] args) {
//        uploadImg();
//        merchant();
        RealNameInfo realNameInfo = RealNameInfo.builder()
                .legalName("张红月")
                .legalLicenceNo("130323199003164221")
                .legalLicenceFrontUrl("[链接]")
                .legalLicenceBackUrl("[链接]")
                .bankCardNo("13050163004300000736")
                .licenceUrl("[链接]")
                .signName("张红月")
                .signType("ENTERPRISE")
                .licenceNo("91130302MABPNT7L08")
                .shortName("秦皇岛得诚科技有限公司")
                .province("130000")
                .city("130300")
                .district("130306")
                .address("河北省秦皇岛市海港区民族路168号聚贤大厦604")
                .contactName("秦皇岛得诚科技有限公司")
                .contactMobile("13780581567")
                .contactEmail("1307780887@qq.com")
                .contactLicenceNo("130323199003164221")
                .adminEmail("1307780887@qq.com")
                .adminMobile("13780581567")
                .build();
        merchant(realNameInfo);
    }

    /**
     * 进件
     */
    public static void merchant(RealNameInfo realName){
        // 创建一个YopRequest对象，指定请求的URL和请求方法
        YopRequest request = new YopRequest("/rest/v2.0/mer/register/saas/merchant", "POST");
        //入网请求号： 自己生成，没有规则要求，但是咱们最好是按规则生成一个，比如KCSM年+月+日+时+分+秒
        request.addParameter("requestNo", "nssb"+ DateUtil.date().toString("yyyyMMddHHmmss"));
        //入网商户业务角色：SETTLED_MERCHANT:入驻商户
        request.addParameter("businessRole", "SETTLED_MERCHANT");
        //商户类型：ENTERPRISE:企业商户-上级商户编号10090206495-固定值
        request.addParameter("parentMerchantNo", "10090206495");
        // 商户主体信息
        MerchantSubjectInfo merchantSubjectInfo = MerchantSubjectInfo.builder()
                .licenceUrl(realName.getOpenAccountLicenceUrl())
                .signName(realName.getSignName())
                .signType(realName.getSignType())
                .licenceNo(realName.getLicenceNo())
                .shortName(realName.getShortName())
                .build();
        request.addParameter("merchantSubjectInfo", JSONUtil.toJsonStr(merchantSubjectInfo));
        // 商户法人信息
        MerchantCorporationInfo merchantCorporationInfo = MerchantCorporationInfo.builder()
                .legalName(realName.getLegalName())
                .legalLicenceType("ID_CARD") //身份证
                .legalLicenceNo(realName.getLegalLicenceNo())
                .legalLicenceFrontUrl(realName.getLegalLicenceFrontUrl())
                .legalLicenceBackUrl(realName.getLegalLicenceBackUrl())
                .build();
        request.addParameter("merchantCorporationInfo", JSONUtil.toJsonStr(merchantCorporationInfo));
        // 商户联系人信息
        MerchantContactInfo merchantContactInfo = MerchantContactInfo.builder()
                .contactName(realName.getContactName())
                .contactMobile(realName.getContactMobile())
                .contactEmail(realName.getContactEmail())
                .contactLicenceNo(realName.getContactLicenceNo())
                .adminEmail(realName.getAdminEmail())
                .adminMobile(realName.getAdminMobile())
                .build();
        request.addParameter("merchantContactInfo", JSONUtil.toJsonStr(merchantContactInfo));
        // 商户行业分类信息
        IndustryCategoryInfo industryCategoryInfo = IndustryCategoryInfo.builder()
                .primaryIndustryCategory("128")
                .secondaryIndustryCategory("128001")
                .build();
        request.addParameter("industryCategoryInfo", JSONUtil.toJsonStr(industryCategoryInfo));
        // 商户经营地址信息
        BusinessAddressInfo businessAddressInfo = BusinessAddressInfo.builder()
                .province(realName.getProvince())
                .city(realName.getCity())
                .district(realName.getDistrict())
                .address(realName.getAddress())
                .build();
        request.addParameter("businessAddressInfo", JSONUtil.toJsonStr(businessAddressInfo));
        // 商户结算账户信息
        SettlementAccountInfo settlementAccountInfo = SettlementAccountInfo.builder()
                .settlementDirection("ACCOUNT") //结算方向：SETTLEMENT_TO_BANK:银行账户结算
                .bankCode("CCB") //（银行代码，代表中国建设银行）
                .bankAccountType("DEBIT_CARD") //（账户类型为借记卡）
                .bankCardNo(realName.getBankCardNo()) //银行账户号码
                .build();
        request.addParameter("settlementAccountInfo", JSONUtil.toJsonStr(settlementAccountInfo));
        //todo 商户通知地址
        request.addParameter("notifyUrl", "https://notify.merchant.com/xxx");
        // 商户产品信息
        ProductInfo productZFB = ProductInfo.builder() //支付宝扫码支付
                .productCode("MERCHANT_SCAN_ALIPAY_OFFLINE") //支付宝扫码
                .rateType("SINGLE_PERCENT") //费率类型：SINGLE_PERCENT：单笔固定百分比费率
                .percentRate("0.3") //费率值：百分比费率值，0.1表示10%
                .fixedRate("")
                .build();
        ProductInfo productWX = ProductInfo.builder() //微信扫码支付
                .productCode("MERCHANT_SCAN_WECHAT_OFFLINE") //支付宝扫码
                .rateType("SINGLE_PERCENT") //费率类型：SINGLE_PERCENT：单笔固定百分比费率
                .percentRate("0.3") //费率值：百分比费率值，0.1表示10%
                .fixedRate("")
                .build();
        ProductInfo productD1 = ProductInfo.builder() //T+1到账等结算相关产品
                .productCode("D1") //支付宝扫码
                .rateType("SINGLE_FIXED") //费率类型：SINGLE_PERCENT：单笔固定百分比费率
                .percentRate("") //费率值：百分比费率值，0.1表示10%
                .fixedRate("1")
                .build();
        request.addParameter("productInfo", JSONUtil.toJsonStr(productWX));
        // 商户产品资质信息
//        request.addParameter("productQualificationInfo", "{ \"paymentScene\": \"RLZYFW\",   \"systemScreenshotUrl\": \"https://staticres.yeepay.com/xxx.文件后缀\",   \"specialPermitProcessUrl\": \"https://staticres.yeepay.com/xxx.文件后缀\",   \"agreementPhotoUrl\": \"https://staticres.yeepay.com/xxx.文件后缀\" }");
        // 商户功能服务
//        request.addParameter("functionService", "[\"SHARE\",\"BACKUP\"]");
        // 商户功能服务资质信息
//        request.addParameter("functionServiceQualificationInfo", "{\"shareScene\":\"FZ_FJ001\",\"shareCertificate\":\"https://staticres.yeepay.com/xxx.文件后缀\",\"alipayBackupCount\":\"5\",\"wechatBackupCount\":\"30\"}");
        // 商户业务场景
//        request.addParameter("businessScene", "{\"businessSceneList\":[\"POS\"],\"isAppIdConfig\":\"YES\",\"appIdConfigType\":\"MERCHANT\",\"appId\":\"121\",\"appSecret\":\"121\"}");
        // 直属代理商编号
//        request.addParameter("directAgentNo", "directAgentNo_example");
        // 商户额外信息
//        request.addParameter("merchantExtraInfo", "{\"groupNo\":\"集团编号\",\"groupName\":\"集团编号\"}");
        // 商户业务通知地址
//        request.addParameter("businessNotifyUrl", "businessNotifyUrl_example");
        // 商户ubo信息列表
//        request.addParameter("uboInfoList", "[{\"name\":\"姓名\",\"type\":\"OWNERSHIP_25_PERCENT\",\"licenceNo\":\"身份证号码\",\"startDate\":\"证件有效期开始时间\",\"address\":\"证件居住地址\",\"expired\":\"有效期结束时间\",\"licenceBackUrl\":\"文件路径\",\"licenceFrontUrl\":\"文件路径\"}]");
        // 商户业务配置
//        request.addParameter("businessConfig", "上送渠道标识：{\"channelConfigs\":[{\"channelIdentifier\":\"渠道号配置-渠道标识1\",\"scene\":\"渠道号配置-场景1\"},{\"channelIdentifier\":\"渠道号配置-渠道标识2\",\"scene\":\"渠道号配置-场景2\"}]}; 上送渠道号示例值：{\"channelConfigs\":[{\"channelNo\":\"渠道号1\"},{\"channelNo\":\"渠道号2\"}]}");
        // 商户协议信息
//        request.addParameter("merchantAgreementInfo", "{\"signatoryName\":\"协议签署人姓名\",\"signatoryMobile\":\"协议签署人手机号\"}");
        // 商户开户信息
//        request.addParameter("bankOpenAccountInfo", "{\"isOpenAccount\":\"是否开立账户\",\"openAccountNoticeUrl\":\"开户结果回调通知\",\"bankCardType\":\"绑定卡类型\",\"bindCardNo\":\"银行卡号\",\"bindAccountName\":\"银行卡户名\",\"bankCode\":\"总行号\",\"branchBankCode\":\"联行号\",\"bankMobile\":\"银行预留手机号\"}");

        try {
            // 发送请求，并获取响应
            YopResponse response = client.request(request);
            // 打印响应结果
            LOGGER.info("result:{}", response.getResult());
        } catch (Exception ex) {
            // 打印异常信息
            LOGGER.error("Exception when calling, ex:", ex);
        }
    }

    /**
     * 上传图片
     */
    public static void uploadImg(){
        YopRequest request = new YopRequest("/yos/v1.0/sys/merchant/qual/upload", "POST");
        request.addParameter("Content-Type", "multipart/form-data");
        request.addMutiPartFile("merQual", new File("E:\\workSpace\\bykj\\需求\\售课系统\\test\\img\\1.jpg"));
        try {
            YosUploadResponse response = client.upload(request);
            LOGGER.info("result:{}", response.getResult());
            System.out.println("====================================================");
            System.out.println(response.getResult());
        } catch (Exception ex) {
            LOGGER.error("Exception when calling, ex:", ex);
        }
    }

    public static String getSign(Map<String,Object> map, String key){
        String result = getStrSort(map);
        result += "key=" + key;
        System.out.println("signStr:{"+result+"}");
//        result = md5(result, encodingCharset).toUpperCase();
        System.out.println("signValue:{"+result+"}");
        return result;
    }


    /**
     * 获取签名串
     * @param map
     * @return  urlParam.append(key).append("=").append( paraMap.get(key) == null ? "" : paraMap.get(key) );
     */
    public static String getStrSort(Map<String,Object> map){
        ArrayList<String> list = new ArrayList<String>();
        for(Map.Entry<String,Object> entry:map.entrySet()){
            if(null != entry.getValue() && !"".equals(entry.getValue())){
                list.add(entry.getKey() + "=" + entry.getValue() + "&");
            }
        }
        int size = list.size();
        String [] arrayToSort = list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < size; i ++) {
            sb.append(arrayToSort[i]);
        }
        return sb.toString();
    }


    public static String md5(String value, String charset) {
        MessageDigest md = null;
        try {
            byte[] data = value.getBytes(charset);
            md = MessageDigest.getInstance("MD5");
            byte[] digestData = md.digest(data);
            return toHex(digestData);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

}

